package com.lyy.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.lyy.yygh.cmn.mapper.DictMapper;
import com.lyy.yygh.cmn.service.DictService;
//import com.lyy.yygh.hosp.mapper.HospitalSetMapper;
//import com.lyy.yygh.hosp.service.HospitalSetService;
import com.lyy.yygh.common.excel.ExcelHelper;
import com.lyy.yygh.model.cmn.Dict;
import com.lyy.yygh.model.hosp.HospitalSet;
import com.lyy.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    /**
     * 根据上级id获取子节点数据
     * @param id
     * @return
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildrenData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> list = baseMapper.selectList(wrapper);
        for (Dict dict : list) {
            Long dictId = dict.getId();
            boolean children = this.isChildren(dictId);
            dict.setHasChildren(children);
        }
        return list;
    }

    /**
     * 导入数据
     * @param file
     */
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importData(MultipartFile file) {
        ExcelHelper fileHelper = new ExcelHelper(DictEeVo.class);
        List<DictEeVo> dictVoList = fileHelper.importExcel(file);
        if(!CollectionUtils.isEmpty(dictVoList)) {
            dictMapper.insertBatch(dictVoList);
        }
    }

    /**
     * 导出数据
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = "dict";
        //设置头信息以下载方式打开
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        //查询数据
        List<Dict> list = baseMapper.selectList(null);
        List<DictEeVo> lists = new ArrayList<>();
        for (Dict dict : list) {
            DictEeVo dictEeVo = new DictEeVo();
            //做一个复制，dict转化成dicteevo
            BeanUtils.copyProperties(dict, dictEeVo);
            lists.add(dictEeVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict").doWrite(lists);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据上级编码与值获取数据字典名称
     * @param s
     * @param value
     * @return
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public String getDictName(String s, String value) {
        System.out.println("s是"+s);
        System.out.println("impl中value"+value);
        System.out.println("StringUtils.isEmpty(s)"+StringUtils.isEmpty(s));
        //如果dict_code为空，就根据value查询
        if(StringUtils.isEmpty(s)){
            System.out.println("走if");
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
            //如果dict_code不为空
        }else{
            System.out.println("走else");
            //根据dict_code查到当前节点
            Dict codeDict = this.getDictByDictCode(s);
            System.out.println("else中的codedict"+codeDict);
            //得到当前的id,继续要查此id下面的节点
            Long parent_id = codeDict.getId();
            System.out.println("else中的cparent_id"+parent_id);
            //根据parent——id和value进行查询
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parent_id)
                    .eq("value", value));
            System.out.println("else中的dict"+dict);
            //得到子节点的名字
            return dict.getName();
        }

    }



    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictcode获取id
        Dict dictByDictCode = this.getDictByDictCode(dictCode);
        List<Dict> childrenData = this.findChildrenData(dictByDictCode.getId());
        //再根据id获取下层的子节点
        return childrenData;
    }




    //根据dict_code得到当前节点
    //@Cacheable(value = "dict",keyGenerator = "keyGenerator")
    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }


    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer integer = baseMapper.selectCount(wrapper);
        return integer > 0;

    }
}
